package com.wanban.download.utils

import android.text.TextUtils
import android.util.Log
import com.wanban.download.ContextProvider
import com.wanban.download.WBDownloadUtils
import com.wanban.download.db.DatabaseManager
import com.wanban.download.db.DownloadEntity
import java.io.File
import java.io.FileNotFoundException

/**
 * 存储路径相关
 */
object PathUtils {

    private const val DOWNLOAD_ROOT_FILE_DIR  = "Wanban"

    /**
     * /Data/Android/xxx/files/Wanban/#{name}/TsList
     */
    const val TS_LIST_FILE_DIR  = "TsList"
    /**
     * /Data/Android/xxx/files/Wanban/#{name}/Keys
     */
    const val KEYS_FILE_DIR  = "Keys"
    /**
     * /Data/Android/xxx/files/Wanban/#{name}/Proxy
     */
    const val PROXY_M3U_FILE_DIR_NAME = "Proxy"
    /**
     * /Data/Android/xxx/files/Wanban/#{name}/Proxy/proxy.m3u
     */
    const val PROXY_M3U_FILE  = "proxy.m3u8"
    /**
     * /Data/Android/xxx/files/Wanban/#{name}/video.mp4
     */
    const val MP4_FILE  = "final.mp4"
    /**
     * /Data/Android/xxx/files/Wanban/#{name}/coverImage.jpg
     */
    const val COVER_IMAGE_FILE  = "coverImage.jpg"

    const val TX_DOWNLOAD_FILE_NAME = "TXDownload"
    const val MEDIA3_DOWNLOAD_FILE_NAME = "Media3"


    fun deleteAllDownloadFiles(){
        val externalFiles = ContextProvider.application.getExternalFilesDirs(DOWNLOAD_ROOT_FILE_DIR)
        externalFiles?.forEach {
            val isDeleteSuccess = it?.deleteRecursively()?:false
            if (isDeleteSuccess) {
                Log.e("DELETE_ALL", "全文文件删除成功！")
            }
        }
    }

    /**
     * /Data/Android/xxx/files/Wanban/
     */
    fun getRootFileDir(): File?{
        val externalFiles = ContextProvider.application.getExternalFilesDirs(DOWNLOAD_ROOT_FILE_DIR)
        if (WBDownloadUtils.isUseSdcardDownload()) {
            val fileDirSize = externalFiles?.size?:0
            if (fileDirSize <= 1) {
                val file = externalFiles.firstOrNull() ?: return null
                if (!file.exists()) {
                    file.mkdirs()
                }
                // 先创建videoName + videoId的路径
                return file
            } else {
                val file = externalFiles[1]?:return null
                if (!file.exists()) {
                    file.mkdirs()
                }
                return file
            }
        } else {
            val file = externalFiles.firstOrNull() ?: return null
            if (!file.exists()) {
                file.mkdirs()
            }
            return file
        }
    }

    fun getTXRootPath(): String? {
        return getRootPath(TX_DOWNLOAD_FILE_NAME)
    }

    fun getMedia3RootPath(): String {
        return getRootFileDir()?.absolutePath + File.separator + MEDIA3_DOWNLOAD_FILE_NAME
    }

    /**
     * 下载文件根路径 /Data/Android/xxx/files/Wanban/#{tag}
     */
    fun getRootPath(tag: String): String? {
        val root = getRootFileDir()?:return null
        return createDownloadPath(root, tag)
    }

    private fun createDownloadPath(rootFile: File, task: DownloadEntity): String{
        val fileAlbum = File(rootFile, task.firstLayerDirName)
        if (!fileAlbum.exists()) {
            fileAlbum.mkdirs()
        }
        val fileEpisodeSource = File(fileAlbum, task.secondLayerDirName)
        if (!fileEpisodeSource.exists()) {
            fileEpisodeSource.mkdirs()
        }
        return fileEpisodeSource.absolutePath
    }

    private fun createDownloadPath(rootFile: File, tag: String): String{
        val fileEpisodeSource = File(rootFile, tag)
        if (!fileEpisodeSource.exists()) {
            fileEpisodeSource.mkdirs()
        }
        return fileEpisodeSource.absolutePath
    }

    /**
     * /Data/Android/xxx/files/Wanban/#{tag}/TsList
     */
    fun getTsListFileDirPath(rootFilePath: String?): String {
        return rootFilePath + File.separator + TS_LIST_FILE_DIR
    }

    /**
     * /Data/Android/xxx/files/Wanban/#{tag}/Keys
     */
    fun getKeyFile(rootPath: String?): File?{
        try {
            if (TextUtils.isEmpty(rootPath)) {
                return null
            }
            val rootFile = File(rootPath!!)
            if (!rootFile.exists()) {
                rootFile.mkdirs()
            }
            val keyDirFile = File(rootPath, KEYS_FILE_DIR)
            if (!keyDirFile.exists()) {
                keyDirFile.mkdirs()
            }
            return keyDirFile
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
            return null
        } catch (e: Exception) {
            e.printStackTrace()
            return null
        }
    }

    /**
     * /Data/Android/xxx/files/Wanban/#{tag}/Proxy/proxy.m3u8
     */
    fun getProxyM3UFile(rootPath: String?): File? {
        try {
            if (TextUtils.isEmpty(rootPath)) {
                return null
            }
            val rootFile = File(rootPath!!)
            if (!rootFile.exists()) {
                rootFile.mkdirs()
            }
            val proxyFileDir = File(rootPath, PROXY_M3U_FILE_DIR_NAME)
            if (!proxyFileDir.exists()) {
                proxyFileDir.mkdirs()
            }
            val proxyFile = File(proxyFileDir, PROXY_M3U_FILE)
            if (!proxyFile.exists()) {
                proxyFile.createNewFile()
            }
            return proxyFile
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
            return null
        } catch (e: Exception) {
            e.printStackTrace()
            return null
        }
    }


    /**
     * /Data/Android/xxx/files/Wanban/#{tag}/final.mp4
     */
    fun getMp4File(rootPath: String?): File? {
        try {
            if (TextUtils.isEmpty(rootPath)) {
                return null
            }
            val rootFile = File(rootPath!!)
            if (!rootFile.exists()) {
                rootFile.mkdirs()
            }
            val mp4File = File(rootPath, MP4_FILE)
            if (!mp4File.exists()) {
                mp4File.createNewFile()
            }
            return mp4File
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
            return null
        } catch (e: Exception) {
            e.printStackTrace()
            return null
        }
    }

    /**
     * /Data/Android/xxx/files/Wanban/#{tag}/coverImage.jpg
     */
    fun getCoverFile(rootPath: String?): File? {
        try {
            if (TextUtils.isEmpty(rootPath)) {
                return null
            }
            val rootFile = File(rootPath!!)
            if (!rootFile.exists()) {
                rootFile.mkdirs()
            }
            val mp4File = File(rootFile, COVER_IMAGE_FILE)
            if (!mp4File.exists()) {
                mp4File.createNewFile()
            }
            return mp4File
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
            return null
        } catch (e: Exception) {
            e.printStackTrace()
            return null
        }
    }


    /**
     * 删除默认下载器下载的文件，包括封面文件
     */
    fun deleteTaskFiles(task: DownloadEntity){
        // 删除文件
        if (!TextUtils.isEmpty(task.fileRootPath)) {
            val file = File(task.fileRootPath!!)
            if (file.exists()) {
                Log.d("DELETE_FILE", "删除 ${task.fileRootPath} 文件...")
                file.deleteRecursively()
            }
            // 判断根目录是否还有其他下载，没的话删除根目录
            val parentFile = file.parentFile
            if (parentFile?.listFiles().isNullOrEmpty()) {
                Log.d("DELETE_FILE", "删除 WanBan 文件目录...")
                parentFile?.deleteRecursively()
            }
        }
        // 清空本地缓存
        CacheM3U8Utils.clearCacheM3U8(task.downloadTag)
    }
}